<?php 
include_once "site_config.php";
header("content-type:text/html; charset=utf-8");
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(1);
date_default_timezone_set('PRC');

session_start();

require_once 'class/ig2sql.class.php';
$db=new ig2sql();
 
$db->ig2_conn(Mysql_server,Mysql_user,Mysql_pass,Mysql_db,'utf8');


function http_request($url, $data = null){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	if (!empty($data)){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	$output = curl_exec($curl);
	curl_close($curl);
	return $output;
}

function ticket_req($access_token,$json){
	$ch = curl_init();//初始化curl
	curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$access_token);//设置链接
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
	curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: text/json');//设置HTTP头
	curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
	curl_setopt($ch, CURLOPT_POSTFIELDS, $json);//POST数据
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	$response = curl_exec($ch);//接收返回信息
	if(curl_errno($ch)){
		//出错则显示错误信息
		echo curl_error($ch);
	}
	curl_close($ch);//关闭curl链接
	return $response;//返回信息
}

function getCode($url,$filename,$dirname){  
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$package = curl_exec($ch);
	$httpinfo = curl_getinfo($ch);
   
	curl_close($ch);
	$media = array_merge(array('mediaBody' => $package), $httpinfo);
	if(!file_exists($dirname)){
		mkdir($dirname,0777,true);
	}
	file_put_contents($dirname.$filename,$media['mediaBody']);
	return $dirname.$filename;
}

function insert_user_role($openid,$tid,$type,$name,$phone,$address){
	$db=new ig2sql();	
	$db->ig2_query("BEGIN");
	$shop=$db->ig2_want('mae_shop','tid="'.$tid.'" and status=1');

    $success = true;
	if($shop){
        // 如果该openid之前注册过，则直接使用当条记录作为新的用户，如果用户所属店铺ID未变，则积分以及兑换记录保留；如果用户所属店铺ID改变，则积分清0，兑换记录清空
        // 如果该openid之前未注册过，则新插入一条用户记录
        $user = $db->ig2_query_select("SELECT * FROM mae_user WHERE openid = '".$openid."' ORDER BY create_time DESC limit 1");
        // 更新逻辑
        if ($user) {
            $user = $user[0];
            // 判断是否更改了门店
            $role = $db->ig2_want('mae_role','uid='.$user['id']);
            $userShop = $db->ig2_want('mae_shop','id = '. $role['shop_id']);

            // 如果没有更改门店，直接将逻辑删除状态改回正常状态即可
            if ($userShop['tid'] == $tid) {
                $success = $db->ig2_query("UPDATE mae_user SET is_delete = 0, role_type = ".$type.", name='".$name."', phone='".$phone."', address='".$address."' WHERE id = ". $user['id']);
                if ($success) {
                    $success = $db->ig2_query("UPDATE mae_role SET is_delete = 0, role_type = ".$type." WHERE uid = ". $user['id']);
                }

                if ($success && $type == 1) {
                    $success = $db->ig2_query("UPDATE `mae_shop` SET `admin_id`=".$user['id'].",`is_activate`=1,`activate_time`=".time()." WHERE tid=".$tid);
                }
                if ($success) {
                    $db->ig2_query("COMMIT");
                    return true;
                } else {
                    $db->ig2_query("ROLLBACK");
                    return false;
                }
            }
            // 如果更改了门店，则需要更换门店的绑定，同时清空所有关联日志记录
            else {

                $success = $db->ig2_query("UPDATE mae_user SET is_delete = 0, sell_count = 0, score = 0, used_score=0, answer_ids = '', is_success = 0, success_time = 0, is_get = 0, get_time = 0, create_time = ".time().", name='".$name."', phone='".$phone."', address='".$address."' WHERE id = ". $user['id']);
                if ($success) {
                    $success = $db->ig2_query("UPDATE mae_role SET is_delete = 0, shop_id=".$shop['id']." WHERE uid = ". $user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_admin_product_exchange_summary_log WHERE userid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_admin_product_exchange_detail_log WHERE userid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_answer_chance_log WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_answer_continue_times WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_award WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_cheap_code_log WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_promocode_exchange_log WHERE userid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_red_pocket_exchange_log WHERE userid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_sell WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_shop_admin_exchange_list WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_shop_admin_get_award WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_shop_user_exchange_list WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_winner WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mae_wish_list WHERE uid = ".$user['id']);
                }
                if ($success) {
                    $success = $db->ig2_query("DELETE FROM mea_user_answer_record WHERE uid = ".$user['id']);
                }

                if ($success && $type == 1) {
                    $success = $db->ig2_query("UPDATE `mae_shop` SET `admin_id`=".$user['id'].",`is_activate`=1,`activate_time`=".time()." WHERE tid=".$tid);
                }
                if ($success) {
                    $db->ig2_query("COMMIT");
                    return true;
                } else {
                    $db->ig2_query("ROLLBACK");
                    return false;
                }
            }
        }
        // 新插逻辑
        else {
            $user_time=time();
            do{
				$user_id=rand(1000,9999).date('YmdHis',$user_time);
				$user_exist=$db->ig2_want('mae_user','id='.$user_id);
			}while($user_exist);

            $success = true;
            $success = $db->ig2_query("INSERT INTO `mae_user`(`id`, `account_id`, `openid`, `role_type`, `sell_count`, `score`, `name`, `phone`, `address`, `is_success`, `success_time`, `is_get`, `get_time`, `create_time`, `is_delete`, `delete_time`) VALUES ('$user_id',16621,'$openid','$type',0,0,'$name','$phone','$address',0,0,0,0,'$user_time',0,0)");

            if ($success) {
                $role_id=rand(1000,9999).date('YmdHis',$user_time);
                $shop_id=$shop['id'];
                $success=$db->ig2_query("INSERT INTO `mae_role`(`id`, `sort_id`, `account_id`, `shop_id`, `uid`, `role_type`, `is_delete`, `delete_time`, `create_time`) VALUES ('$role_id',NULL,16621,'$shop_id','$user_id','$type',0,0,'$user_time')");
            }

            if ($success && $type == 1) {
                $success = $db->ig2_query("UPDATE `mae_shop` SET `admin_id`=$user_id,`is_activate`=1,`activate_time`=".$user_time." WHERE tid=".$tid);
            }

            if ($success) {
                $db->ig2_query("COMMIT");
                return true;
            } else {
                $db->ig2_query("ROLLBACK");
                return false;
            }
        }
//		while(true){
//			$user_time=time();
//			do{
//				$user_id=rand(1000,9999).date('YmdHis',time());
//				$user_out=$db->ig2_want('mae_user_out','id='.$user_id);
//			}while($user_out);
//
//			$res1=$db->ig2_query("INSERT INTO `mae_user`(`id`, `account_id`, `openid`, `role_type`, `sell_count`, `score`, `name`, `phone`, `address`, `is_success`, `success_time`, `is_get`, `get_time`, `create_time`) VALUES ('$user_id',16621,'$openid','$type',0,0,'$name','$phone','$address',0,0,0,0,'$user_time')");
//
//			$role_time=time();
//			$role_id=rand(1000,9999).date('YmdHis',time());
//			$shop_id=$shop['id'];
//			$res2=$db->ig2_query("INSERT INTO `mae_role`(`id`, `sort_id`, `account_id`, `shop_id`, `uid`, `role_type`, `is_delete`, `delete_time`, `create_time`) VALUES ('$role_id',NULL,16621,'$shop_id','$user_id','$type',0,0,'$role_time')");
//
//			if($res1 && $res2){
//				if($type==1){
//					$res3=$db->ig2_query("UPDATE `mae_shop` SET `admin_id`=$user_id,`is_activate`=1,`activate_time`=".time()." WHERE tid=".$tid);
//					if($res3){
//						$db->ig2_query("COMMIT");
//						//$return_arr=array($user_id,$role_id);
//						//return $return_arr;
//						return true;
//					}else{
//						$db->ig2_query("ROLLBACK");
//						insert_user_role($openid,$tid,$type,$name,$phone,$address);
//					}
//				}else{
//					$db->ig2_query("COMMIT");
//					//$return_arr=array($user_id,$role_id);
//					//return $return_arr;
//					return true;
//				}
//			}else{
//				$db->ig2_query("ROLLBACK");
//				insert_user_role($openid,$tid,$type,$name,$phone,$address);
//			}
//		}
	}else{
		return false;
	}
}

function is_exists($field,$table,$value_arr){
	$db=new ig2sql();
	
	$rand_id=$value_arr[$field];
	$exists=$db->ig2_want($table,$field.'="'.$rand_id.'"');
	
	if($exists){
		$rand_id=rand(1000,9999).date('YmdHis',time());
		$value_arr[$field]=$rand_id;
		is_exists($field,$table,$value_arr);
	}else{
		$db->ig2_insert($table,$value_arr);
		$new_data=$db->ig2_want($table,$field.'="'.$rand_id.'"');
		return $new_data;
	}
}

function tellgoto($tell,$goto){
	if($tell){
		echo "<script language=javascript>alert('".$tell."');</script>";
		echo "<script language=javascript>document.location.href='".$goto."';</script>";
	}else{
		echo "<script language=javascript>document.location.href='".$goto."';</script>";
	}
}

?>